package com.zfzs.post.rest;

import com.zfzs.post.common.bean.ResponseResult;
import com.zfzs.post.utils.SecurityUtils;
import com.zfzs.post.aop.log.Log;
import com.zfzs.post.modules.domain.Picture;
import com.zfzs.post.service.PictureService;
import com.zfzs.post.modules.dto.PictureQueryCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 郑杰
 * @date 2018/09/20 14:13:32
 */
@RestController
@RequestMapping("/api")
public class PictureController {

    @Autowired
    private PictureService pictureService;

    @Log("查询图片")
    @PreAuthorize("hasAnyRole('ADMIN','PICTURE_ALL','PICTURE_SELECT')")
    @GetMapping(value = "/pictures")
    public ResponseResult getRoles(PictureQueryCriteria criteria, Pageable pageable) {
        return ResponseResult.ok(pictureService.queryAll(criteria, pageable));
    }

    /**
     * 上传图片
     *
     * @param file
     * @return
     * @throws Exception
     */
    @Log("上传图片")
    @PreAuthorize("hasAnyRole('ADMIN','PICTURE_ALL','PICTURE_UPLOAD')")
    @PostMapping(value = "/pictures")
    public ResponseResult upload(@RequestParam MultipartFile file) {
        String userName = SecurityUtils.getUsername();
        Picture picture = pictureService.upload(file, userName);
        Map map = new HashMap(3);
        map.put("errno", 0);
        map.put("id", picture.getId());
        map.put("data", new String[]{picture.getUrl()});
        return ResponseResult.ok(map);
    }

    /**
     * 删除图片
     *
     * @param id
     * @return
     */
    @Log("删除图片")
    @PreAuthorize("hasAnyRole('ADMIN','PICTURE_ALL','PICTURE_DELETE')")
    @DeleteMapping(value = "/pictures/{id}")
    public ResponseResult delete(@PathVariable Long id) {
        pictureService.delete(pictureService.findById(id));
        return ResponseResult.ok();
    }

    /**
     * 删除多张图片
     *
     * @param ids
     * @return
     */
    @Log("删除图片")
    @PreAuthorize("hasAnyRole('ADMIN','PICTURE_ALL','PICTURE_DELETE')")
    @DeleteMapping(value = "/pictures")
    public ResponseResult deleteAll(@RequestBody Long[] ids) {
        pictureService.deleteAll(ids);
        return ResponseResult.ok();
    }
}
